import os
import logging
import time
import pyautogui
from pywinauto.application import Application
import pygetwindow as gw
from  ...config import Config
from  .autoOperate import (
    click_button,
    input_text,
    input_text1,
    open_window,
    get_address,
    click_point,  # 确保此处已导入 click_point
    input_text2, clear_input_box
)

# 设置日志配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

static_path = Config.AUTO_OPERATE_PATH

# 定义UI元素、操作和坐标点的配置对象
UI_CONFIG = {
    "weChat": {
        "window_name": "微信",
        "address_book": 'tongxunlu',
        "add_friend_button": 'tianjia',
        "add_friend_input": 'tianjiahaoyouinput',
        "home_button": 'home',
        "click_points": {
            "confirm_add_friend": (355, 149),
            "next_step": (479, 277),
            "finish_add": (876, 968)
        }
    },
    "friend_management": {
        "search_box": 'modify/search',
        "change_name_button": 'modify/changename',
        "confirm_button": 'modify/confirm',
        "click_points": {
            "search_confirm": (1896, 54),
            "select_contact": (1635, 174),
            "edit_contact": (1580, 230)
        }
    },
    "group_management": {
        "add_icon": 'group/addicon',
        "confirm_dot": 'group/okdot',
        "delete_dot": 'group/deldot',
        "confirm_button": 'group/ok',
        "search_box": 'group/search',
        "click_points": {
            "group_confirm": (598, 970)
        }
    }
}

# 动态获取UI地址的辅助函数
def get_ui_address(section, key):
    return get_address(static_path, UI_CONFIG[section][key])

# 动态获取坐标点的辅助函数
def get_click_point(section, key):
    return UI_CONFIG[section]["click_points"][key]

# 动态点击坐标点的辅助函数
def click_at_point(section, key):
    x, y = get_click_point(section, key)
    click_point(x, y)

# 好友管理：通过微信号或手机号添加好友
def add_friend(friend_info):
    try:
        if open_window(UI_CONFIG["weChat"]["window_name"]):
            logging.info("微信打开成功")

            if click_button(get_ui_address("weChat", "address_book")):
                logging.info("点击通讯录成功")

                if click_button(get_ui_address("weChat", "add_friend_button")):
                    logging.info("点击添加好友按钮成功")

                    if click_button(get_ui_address("weChat", "add_friend_input")):
                        logging.info("点击输入框成功")

                        if input_text(friend_info):
                            pyautogui.click(get_click_point("weChat", "confirm_add_friend"))
                            time.sleep(0.5)
                            pyautogui.click(get_click_point("weChat", "next_step"))
                            time.sleep(1)
                            pyautogui.click(get_click_point("weChat", "finish_add"))

                            if click_button(get_ui_address("weChat", "home_button")):
                                logging.info("返回聊天页面")
                                return {"code": 200, "msg": "添加好友成功"}
                            else:
                                logging.error("点击返回主页失败")
                                return {"code": 233, "msg": "点击返回主页失败"}
                    else:
                        logging.error("点击输入框失败")
                        return {"code": 233, "msg": "点击输入框失败"}
                else:
                    logging.error("点击添加好友按钮失败")
                    return {"code": 233, "msg": "点击添加好友按钮失败"}
            else:
                logging.error("点击通讯录失败")
                return {"code": 233, "msg": "点击通讯录失败"}
        else:
            logging.error("打开微信失败")
            return {"code": 233, "msg": "打开微信失败"}
    except Exception as e:
        logging.error(f"发生异常: {e}")
        return {"code": 500, "msg": "内部错误"}

# 好友管理：修改好友备注
def change_friend_remark(friend_info, remark_name):
    try:
        if open_window(UI_CONFIG["weChat"]["window_name"]):
            logging.info("微信打开成功")

            if click_button(get_ui_address("friend_management", "search_box")):
                logging.info("点击搜索框成功")

                if input_text1(friend_info):
                    logging.info("输入微信号成功")
                    click_at_point("friend_management", "search_confirm")
                    time.sleep(1)
                    click_at_point("friend_management", "select_contact")
                    time.sleep(1)
                    click_at_point("friend_management", "edit_contact")

                    if click_button(get_ui_address("friend_management", "change_name_button")):
                        logging.info("点击修改备注成功")
                        clear_input_box()
                        input_text1(remark_name)

                        if click_button(get_ui_address("friend_management", "confirm_button")):
                            logging.info("点击保存成功")
                            if click_button(get_ui_address("weChat", "home_button")):
                                logging.info("返回聊天页面")
                                return {"code": 200, "msg": "修改备注成功"}
                            else:
                                logging.error("返回聊天页面失败")
                                return {"code": 233, "msg": "返回聊天页面失败"}
                        else:
                            logging.error("点击保存失败")
                            return {"code": 233, "msg": "点击保存失败"}
                    else:
                        logging.error("点击修改备注失败")
                        return {"code": 233, "msg": "点击修改备注失败"}
                else:
                    logging.error("输入微信号失败")
                    return {"code": 233, "msg": "输入微信号失败"}
            else:
                logging.error("点击搜索框失败")
                return {"code": 233, "msg": "点击搜索框失败"}
        else:
            logging.error("打开微信失败")
            return {"code": 233, "msg": "打开微信失败"}
    except Exception as e:
        logging.error(f"发生异常: {e}")
        return {"code": 500, "msg": "内部错误"}

# 群聊管理：拉群
def pull_group(group_info, hello_word):
    try:
        if open_window(UI_CONFIG["weChat"]["window_name"]):
            logging.info("微信打开成功")

            if click_button(get_ui_address("group_management", "add_icon")):
                logging.info("点击加群成功")

                for itemname in group_info:
                    input_text(itemname)

                    if click_button(get_ui_address("group_management", "confirm_dot")):
                        logging.info("点击确认成功")

                        if click_button(get_ui_address("group_management", "delete_dot")):
                            logging.info("清除成功")
                        else:
                            logging.error("清除失败")
                            return {"code": 233, "msg": "清除失败"}
                    else:
                        logging.error("点击确认失败")
                        return {"code": 233, "msg": "点击确认失败"}

                if click_button(get_ui_address("group_management", "confirm_button")):
                    logging.info("点击确定成功")
                    time.sleep(1)
                    click_at_point("group_management", "group_confirm")
                    input_text2(hello_word)
                    return {"code": 200, "msg": "拉群成功"}
                else:
                    logging.error("点击确定失败")
                    return {"code": 233, "msg": "点击确定失败"}
            else:
                logging.error("点击加群失败")
                return {"code": 233, "msg": "点击加群失败"}
        else:
            logging.error("打开微信失败")
            return {"code": 233, "msg": "打开微信失败"}
    except Exception as e:
        logging.error(f"发生异常: {e}")
        return {"code": 500, "msg": "内部错误"}

# 群聊管理：修改群名称
def change_group_name(group_info, hello_word):
    try:
        if open_window(UI_CONFIG["weChat"]["window_name"]):
            logging.info("微信打开成功")

            if click_button(get_ui_address("group_management", "search_box")):
                logging.info("点击搜索框成功")
                return {"code": 200, "msg": "点击搜索框成功"}
            else:
                logging.error("点击搜索框失败")
                return {"code": 233, "msg": "点击搜索框失败"}
        else:
            logging.error("打开微信失败")
            return {"code": 233, "msg": "打开微信失败"}
    except Exception as e:
        logging.error(f"发生异常: {e}")
        return {"code": 500, "msg": "内部错误"}

# 重试机制函数
def retry_on_failure(func, *args, max_retries=3):
    """
    重试一个函数，直到成功或达到最大重试次数。

    :param func: 要重试的函数
    :param args: 函数参数
    :param max_retries: 最大重试次数，默认为3
    :return: 函数的结果
    """
    retries = 0
    while retries < max_retries:
        result = func(*args)
        if result["code"] != 233:
            return result
        retries += 1
        logging.warning(f"重试第 {retries} 次...")
    logging.error("达到最大重试次数，操作失败")
    return result

# 测试函数
if __name__ == "__main__":
    result = retry_on_failure(change_friend_remark, "肖敏新备注", "肖敏")
    print(result)
